//
//  ChatListViewController.m
//  moon
//
//  Created by beyself on 16/6/18.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "ChatListViewController.h"
#import "ChatViewController.h"
#import "PrivateViewController.h"

@interface ChatListViewController ()<RCIMUserInfoDataSource>

@end

@implementation ChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"互动";
    self.view.backgroundColor = BG;
    
    _mUserInfo = [[NSMutableDictionary alloc] init];
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE)]];
   
    
    NSDictionary* info = (NSDictionary*)[Utils loadCustomObjectWithKey:ALL_MEMBER];
    [_mUserInfo setDictionary:info];
    
    self.conversationListTableView.tableFooterView = [[UIView alloc] init];
    self.conversationListTableView.backgroundColor = BG;
    
    NSArray* array = APPDELEGATE.mMemberInfo[@"classes"];
    UIView* head = [[UIView alloc] init];
    head.frame = CGRectMake(0, 0, SCREEN_WIDTH, array.count*64 + 10);
    head.backgroundColor = BG;
    self.conversationListTableView.tableHeaderView = head;
    
    for(int i = 0; i < array.count; i++)
    {
        NSDictionary* item = array[i];
        NSString* className = item[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = item[@"class_name"];
        
        UIButton* button  = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 2100 + i;
        button.frame = CGRectMake(0, 64*i, SCREEN_WIDTH, 64);
        button.titleLabel.font = FONT_15;
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 60, 0, 0);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:TEXT forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:className forState:UIControlStateNormal];
        [button setTitle:[item[@"id"] description] forState:UIControlStateDisabled];
        
        UIImageView* imageview = [[UIImageView alloc] init];
        imageview.frame = CGRectMake(10, 10, 44, 44);
        imageview.image = [UIImage imageNamed:@"chat_class"];
        imageview.layer.cornerRadius = 22;
        imageview.layer.masksToBounds = YES;
        [button addSubview:imageview];
        
        UILabel* label = [[UILabel alloc] init];
        label.frame = CGRectMake(45, 13, 18, 18);
        label.textColor = WHITE;
        label.backgroundColor = [UIColor redColor];
        label.font = FONT_12;
        label.hidden = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 9;
        label.layer.masksToBounds = YES;
        label.tag = 101;
        [button addSubview:label];
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 63.5, SCREEN_WIDTH, .5);
        layer.backgroundColor = LINE.CGColor;
        [button.layer addSublayer:layer];
        [head addSubview:button];
    }
    
    [RCIM sharedRCIM].userInfoDataSource = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUnread) name:@"receive_msg" object:nil];
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
    ChatViewController *conversationVC = [[ChatViewController alloc]init];
    conversationVC.conversationType = model.conversationType;
    conversationVC.targetId = model.targetId;
    conversationVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:conversationVC animated:YES];
}

- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *userInfo))completion
{
    NSDictionary* userInfo = _mUserInfo[userId];
    RCUserInfo *users=[RCUserInfo new];
    
    if (completion && userInfo && userInfo.count) {
        NSString* path = @"";
        if([Utils isStringNullOrEmpty:[userInfo[@"avatar"] description]])
        {
            if([userInfo[@"is_teacher"] intValue] == 1)
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png";
            }
            else
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
            }
        }
        else path = [NSString stringWithFormat:@"%@%@",IMG_URL,userInfo[@"avatar"]];
        
        users.portraitUri = path;
        users.name = [self getUsername:userId];
        users.userId = userId;
        [RCIM sharedRCIM].enableMessageAttachUserInfo=YES;
        
        completion(users);
    }
    else
    {
        users.portraitUri = @"http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
        users.name = @"服务器未找到";
        users.userId = userId;
        [RCIM sharedRCIM].enableMessageAttachUserInfo=YES;
        
        completion(users);
    }
}

- (NSString*) getUsername:(NSString*)userId
{
    NSDictionary* dic = _mUserInfo;
    if(!dic || !dic.count) return @"";
    
    NSDictionary* user = dic[userId];
    if(!user || !user.count) return @"";
    
    NSString* username = user[@"alias"];
    if([Utils isStringNullOrEmpty:username]) username = user[@"username"];
    
    return username;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.showConnectingStatusOnNavigatorBar = NO;
    [APPDELEGATE setChatUnread];
}

- (void) setUnread
{
    NSArray* array = APPDELEGATE.mMemberInfo[@"classes"];
    UIView* heaview = self.conversationListTableView.tableHeaderView;
    
    for(int i = 0; i < array.count; i++)
    {
        NSDictionary* item = array[i];
        NSString* className = item[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = item[@"class_name"];
        [(UIButton*)[heaview viewWithTag:2100 + i] setTitle:className forState:UIControlStateNormal];
        
        int left = [[RCIMClient sharedRCIMClient] getUnreadCount:ConversationType_GROUP
                                                        targetId:[item[@"id"] description]];
        UILabel* label = (UILabel*)[[heaview viewWithTag:2100 + i] viewWithTag:101];
        label.hidden = YES;
        if(left > 0)
        {
            label.hidden = NO;
            [label setText:[NSString stringWithFormat:@"%d",left]];
        }
    }

}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.showConnectingStatusOnNavigatorBar = YES;
    [self setUnread];
    [self getAllMember];
    [APPDELEGATE setChatUnread];
}

- (void) buttonClick:(UIButton*)btn
{
    ChatViewController *chat = [[ChatViewController alloc]init];
    chat.hidesBottomBarWhenPushed = YES;
    chat.conversationType = ConversationType_GROUP;
    chat.targetId = [btn titleForState:UIControlStateDisabled];
    [self.navigationController pushViewController:chat animated:YES];
}

- (void) getAllMember
{
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
    [Utils sendHttpPostNOWait:param method:@"get_my_group_member_list" controller:self flag:0];
}

- (void) refreshOnMain:(RCUserInfo*)user
{
    [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:user.userId];
}

- (void) refreshMember
{
    NSDictionary* userInfo = _mUserInfo;
    NSArray* array = [userInfo allValues];
    for(NSDictionary* item in array)
    {
        NSString* userId = [item[@"id"] description];
        
        NSString* path = @"";
        if([Utils isStringNullOrEmpty:[item[@"avatar"] description]])
        {
            if([item[@"is_teacher"] intValue] == 1)
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png";
            }
            else
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
            }
        }
        else path = [NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar"]];
        
        RCUserInfo *users=[RCUserInfo new];
        users.portraitUri = path;
        users.name = [self getUsername:userId];
        users.userId = userId;
        
        [self performSelectorOnMainThread:@selector(refreshOnMain:) withObject:users waitUntilDone:YES];
    }
}

- (void) httpCallback:(NSDictionary*)data flag:(int)flag
{
    if(flag == 0)
    {
        [Utils saveCustomObject:data[@"members"] key:ALL_MEMBER];
        [_mUserInfo setDictionary:data[@"members"]];
        [NSThread detachNewThreadSelector:@selector(refreshMember) toTarget:self withObject:nil];
    }
}

- (void) httpCallbackFail:(int)flag
{
    
}

- (void) showAllTextDialog:(NSString*)msg {
    MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:APPDELEGATE.window];
    [APPDELEGATE.window addSubview:HUD];
    HUD.labelText = msg;
    HUD.mode = MBProgressHUDModeText;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        
    }];
}

- (void) showWaitDialog {
    //初始化进度框，置于当前的View当中
    _mMBProgressHUD = [[MBProgressHUD alloc] initWithView:APPDELEGATE.window];
    [APPDELEGATE.window addSubview:_mMBProgressHUD];
    
    //如果设置此属性则当前的view置于后台
    _mMBProgressHUD.dimBackground = YES;
    
    //设置对话框文字
    _mMBProgressHUD.labelText = @"正在加载...";
    
    //显示对话框
    [_mMBProgressHUD showAnimated:YES whileExecutingBlock:^{
        
    } completionBlock:^{
        
    }];
}

- (void) showMsg:(NSString*)msg
{
    UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:nil message:msg
                                                    delegate:nil
                                           cancelButtonTitle:nil
                                           otherButtonTitles:@"确定", nil];
    [dialog show];
}

- (void) dissmissDialog
{
    [_mMBProgressHUD removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
